<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/25
 * Time: 16:35
 */

namespace app\common\model;


use think\facade\Config;
use think\facade\Filesystem;
use think\facade\Request;

class UploadFile
{
    #允许上传文件大小单位MB
    private $size = 2;
    #允许上传的文件后缀
    private $allow_all_extension = [
        "jpg",
        "png"
    ];
    #源文件大小
    private $original_size = "";
    #源文件名称
    private $original_name = "";
    #源文件扩展名
    private $original_extension = "";

    public function uploadFile($file,$folder_name)
    {
        #获取文件基本信息
        self::getFileInfo($file);

        #验证文件大小,需要转化为B
        if( $this->original_size >= ($this->size)*1048576 )
        {
            returnJson(-2004,"资源超过最大限制".$this->size."MB");
        }
        if( !in_array( strtolower($this->original_extension), $this->allow_all_extension ) )
        {
            returnJson(-2004,"当前上传文件扩展类型不支持");
        }
        #文件上传
        return self::getReturnDate($folder_name,$file);
    }
    #return 文件基本信息
    private function getReturnDate($folder_name,$file)
    {
        #源文件名称
        $resources['original_name'] = $this->original_name;
        #文件大小
        $resources['resources_size'] = self::fileUnitConversion($this->original_size);
        $resources['resources_extension'] = $this->original_extension;
        #当前访问域名
        $resources['domain_name'] = Request::domain();
        #新文件名称
        $new_name = Filesystem::disk('public')->putFile( $folder_name, $file );
        $url = Config::get('filesystem')['disks']['public']['url'];
        $resources['new_name'] = getForwardSlash($url.$new_name);
        return $resources;
    }
    #获取文件基本信息
    private function getFileInfo($file)
    {
        #源文件名称
        $this->original_name = $file->getOriginalName();
        #源文件扩展
        $this->original_extension = $file->getOriginalExtension();
        #源文件大小
        $this->original_size = $file->getSize();
    }
    #文件转化对应大小单位
    private function fileUnitConversion($size)
    {
        #文件大小计算
        if($size/1024 < 1)
        {
            $new_size = $size."B";
        }else if($size/1024 < 1024)
        {
            $new_size = sprintf("%.2f",$size/1024)."KB";
        }else{
            $new_size = sprintf("%.2f",$size/1024/1024)."MB";
        }
        return $new_size;
    }

}